<?php
declare(strict_types=1);

namespace app\middleware;

use app\exceptions\LoginException;
use app\exceptions\ParamsLackException;
use app\exceptions\SystemException;
use app\Request;
use app\utils\AppRespUtil;
use think\facade\Log;

/**
 * 登录校验的一个中间件
 *
 * @package app\middleware
 */
class AuthMiddleware
{
    /**
     * 处理登录校验
     *
     * @param Request $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     * @throws LoginException
     * @throws ParamsLackException
     * @throws SystemException
     */
    public function handle(Request $request, \Closure $next)
    {
        if($request->isOptions()){
            return AppRespUtil::success();
        }
        // 校验
        if (!$request->isPost()) {
            throw new SystemException('请求错误');
        }
        if (!$token = $request->header('token', '')) {
            throw new LoginException();
        }
        if (!$userInfo = app('app\services\CacheService')->getUserInfo($token)) {//获取用户信息
            throw new LoginException();
        }
        $request->setUser($userInfo);
        return $next($request);
    }
}